package com.dai.zhenfujin.visitingcard;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dai.zhenfujin.AccountPasswordActivity;
import com.dai.zhenfujin.BaseAdapter.BaseViewHolder;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.Constants.EventConstants;
import com.dai.zhenfujin.MainActivity;
import com.dai.zhenfujin.R;
import com.dai.zhenfujin.adapter.VisitingTypeAdpter;
import com.dai.zhenfujin.base.BaseFragment;
import com.dai.zhenfujin.bean.MessageEvent;
import com.dai.zhenfujin.bean.ProListBean;
import com.dai.zhenfujin.bean.TypeListBean;
import com.dai.zhenfujin.bean.VersionBean;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.my.activity.WalletActivity;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.utils.UIUtils;
import com.dai.zhenfujin.visitingcard.activity.FansActivity;
import com.dai.zhenfujin.visitingcard.activity.Roomtivity;
import com.dai.zhenfujin.visitingcard.adapter.VisitingCardAdapter2;
import com.dai.zhenfujin.visitingcard.app.LocationActiviy;
import com.dai.zhenfujin.visitingcard.app.ParticularsPageActivity;
import com.dai.zhenfujin.visitingcard.bean.VisitingCardBean;
import com.google.gson.Gson;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.dai.zhenfujin.Constants.EventConstants.PUBLISH_DYNAMIC;

/**
 * 名片列表
 */
public class VisitingcardFragment extends BaseFragment implements View.OnClickListener {

    private View view;
    private ListView listView;
    private LinearLayout iv_alum;
    private ImageView iv_no_msg;
    private View vHead, view_line;
    private VisitingCardAdapter2 adapter;
    private GridView rv_type;
    private List<VisitingCardBean> visitingCardBeans;

    //head
    private TextView tvLoculus, tvCar, tvMarry, tvelse, tvfans;

    private TextView tvLocation, message_search;
    private ImageView iv_alum2;
    private int page = 1;
    private int number = 10;
    private List<TypeListBean.TypelistBean> typeList = new ArrayList<>();
    private List<ProListBean.ProListBean2> proListBBean = new ArrayList<>();
    private VisitingTypeAdpter typeListAdapter;
    public static MainActivity context2;
    private TypeListBean typeListBean;
    private SmartRefreshLayout refreshLayout;
    private PopupWindow mPopWindow, mPopWindow2;
    private String user_id;
    private Double latitude;
    private Double longitude;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View initView() {
        context2 = (MainActivity) getActivity();
        view = View.inflate(mContext, R.layout.fragment_visitingcard, null);//potato
        listView = (ListView) view.findViewById(R.id.visiting_lsitview);
        tvLocation = (TextView) view.findViewById(R.id.visiting_location);
        //发布
        iv_alum = view.findViewById(R.id.iv_alum);
        iv_alum2 = view.findViewById(R.id.iv_alum2);
        message_search = (TextView) view.findViewById(R.id.message_search);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        iv_no_msg = view.findViewById(R.id.iv_no_msg);
        vHead = View.inflate(mContext, R.layout.fragment_visitingcard_head2, null);
        rv_type = vHead.findViewById(R.id.grid_view);
        view_line = vHead.findViewById(R.id.view_line);
        String city = SPUtils.getString(context2, "city");
        if (!TextUtils.isEmpty(city)){
            if (city.contains("市")){
                tvLocation.setText(city.split("市")[0]);
            }else {
                tvLocation.setText(city);
            }
        }

        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }

    @Override
    public void onPause() {
        super.onPause();
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event != null && event.getMessageKey() != null) {
            if (event.getMessageKey().equals(EventConstants.UPDATA_PRODUCT_LIST)) {
                page = 1;
                getProductList(true);
            }
        }
    }


    @Override
    public void initData() {
        super.initData();
        listView.addHeaderView(vHead);
        adapter = new VisitingCardAdapter2(mContext, proListBBean);
        listView.setAdapter(adapter);

        visitingCardBeans = new ArrayList<>();
        rv_type.setNumColumns(5);
        typeListAdapter = new VisitingTypeAdpter(mContext, typeList);
        rv_type.setAdapter(typeListAdapter);
        //隐藏进度条（不管有没有活动都隐藏）
        listView.setVerticalScrollBarEnabled(false);
        if (!EaseCommonUtils.isNetWorkConnected(getContext())) {
            String json = SPUtils.getString(context2,"json");
             typeListBean =  new Gson().fromJson(json, TypeListBean.class);
             if (null != typeListBean)
             typeList.addAll(typeListBean.getTypeList());
             typeListAdapter.notifyDataSetChanged();
        }else {
            getHeadTypeInfo();
        }
      //  clearSPUtils();
        initRefresh();
        initListener();
      //  int showRed = getArguments().getInt("showRed");
        user_id = SPUtils.getString(getActivity(), Constants.USER_MOBILE);
        if (SPUtils.getBoolean(getActivity(),"login")){  //true
            if (SPUtils.getBoolean(getActivity(),"regist")) { //是否注册
                view.postDelayed(() -> showRed(), 1000);
            }
        }
    }

    private void clearSPUtils() {
        Map<String, ?> all = com.hyphenate.easeui.utils.SPUtils.getAll(mContext);
        for(String key : all.keySet()){
            if (key.contains("friend_id")){
                String  key1 = key;
                Logger.d("EditCreateGroup-----" + key1);
                com.hyphenate.easeui.utils.SPUtils.saveConversionJob3(mContext,key1,false);
            }
           if (key.contains("gif")){
                String  key2 = key;
                Logger.d("EditCreateGroup-----" + key2);
                com.hyphenate.easeui.utils.SPUtils.saveConversionGif2(mContext,key2,false);
            }
        }
    }

    private void checkVersion() {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params.put("req_bd", params2);
        HttpClient.post(getActivity(), Constants.CHECKVERSION, params, new CallBack<VersionBean>() { //RESULT
            @Override
            public void onSuccess(VersionBean resultBean) {
                onRefresh();
                if (resultBean.getStatus() == 1) {  //有版本更新
                    view.postDelayed(() -> showVision(resultBean), 1000);
                }
            }
        });
    }

    private void showVision(VersionBean resultBean) {
        Dialog dialog = new Dialog(getActivity(), R.style.dialog);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_version_info, null);
        TextView tv_ver = view.findViewById(R.id.tv_ver);
        TextView tv_desc = view.findViewById(R.id.tv_desc);
        TextView cancel = view.findViewById(R.id.cancel);
        TextView submit = view.findViewById(R.id.submit);
        tv_ver.setText("版本:" + resultBean.getV_ver());
        tv_desc.setText(resultBean.getV_desc());

        cancel.setOnClickListener(v -> dialog.dismiss());

        submit.setOnClickListener(v -> {
            String url = resultBean.getV_url();
            Uri uri = Uri.parse(url);
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(it);
            dialog.dismiss();
        });
        //点即不消失
        dialog.setCancelable(false);
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        if (window == null) {
            return;
        }
        dialog.show();//显示对话框
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = dm.widthPixels - 300;
        window.setAttributes(lp);
    }


    private void showRed() {
        setBackgroundAlpha((float) 0.4);
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_red_info, null);
        ImageView iv_red = contentView.findViewById(R.id.iv_red);
        if (!TextUtils.isEmpty(SPUtils.getString(mContext,"invite"))){
            iv_red.setImageResource(R.mipmap.red2);
        }

        ImageView iv_close = contentView.findViewById(R.id.iv_close);
        iv_close.setOnClickListener(v -> mPopWindow.dismiss());

        iv_red.setOnClickListener(v -> {
            startActivity(new Intent(getActivity(), WalletActivity.class));
            mPopWindow.dismiss();
        });

        mPopWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.activity_main, null);
        mPopWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0);
        mPopWindow.setOnDismissListener(() -> setBackgroundAlpha(1));
        SPUtils.saveShow(getActivity(), user_id, true);
        SPUtils.put(getActivity(),"regist",false);
    }

    private void setBackgroundAlpha(float v) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = v;
        getActivity().getWindow().setAttributes(lp);
    }

    private void getHeadTypeInfo() {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params2.put("type_id", 0 + "");
        params.put("req_bd", params2);
        HttpClient.post(mContext, Constants.TYPELIST, params, new CallBack<TypeListBean>() {
            @Override
            public void onSuccess(TypeListBean resultBean) {
                typeListBean = resultBean;
                typeList.clear();
                if (null != resultBean)
                typeList.addAll(resultBean.getTypeList());
                typeListAdapter.notifyDataSetChanged();
                checkVersion();
            }
        });
    }

    private void initRefresh() {
        refreshLayout.setOnRefreshListener(refreshLayout -> refreshLayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                getHeadTypeInfo();
              //  page = 1;
             //   getProductList(true);
                refreshLayout.finishRefresh();
                refreshLayout.resetNoMoreData();
            }
        }, 1500));

        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                getProductList(false);
            }
        });
    }

    private void onRefresh() {
      //  getHeadTypeInfo();
        page = 1;
        getProductList(true);
    }


    /**
     * 查询名片列表
     */
    private void getProductList(boolean isRefresh) { //
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params2.put("type_id", 0 + "");
        params2.put("words", "");
        params2.put("page", page + "");
        params2.put("number", number + "");
        if (null == latitude) {
            params2.put("loc_x", SPUtils.getString(context2, "longitude"));
            params2.put("loc_y", SPUtils.getString(context2, "latitude"));
            Log.i("main------",SPUtils.getString(context2, "longitude"));
            Log.i("main------",SPUtils.getString(context2, "latitude"));
        } else {
            params2.put("loc_x", longitude + "");
            params2.put("loc_y", latitude + "");
            Log.i("main---",longitude + "");
            Log.i("main---",latitude + "");
        }
        params.put("req_bd", params2);
        HttpClient.post(mContext, Constants.PRODUCTLIST, params, new CallBack<ProListBean>() {
            @Override
            public void onSuccess(ProListBean proListBean) {
                if (isRefresh) {
                    proListBBean.clear();
                    if (proListBean.getProList().size() == 0){
                        proListBBean.addAll(proListBean.getProList());
                        adapter.notifyDataSetChanged();
                        return;
                    }
                    page = 2;
                } else {
                    page++;
                    refreshLayout.finishLoadmore();
                }
                if (proListBean.getProList().size() > 0) {
                    proListBBean.addAll(proListBean.getProList());
                    adapter.notifyDataSetChanged();
                } else {
                    refreshLayout.finishLoadmoreWithNoMoreData();//将不会再次触发加载更多事件
                }
            }
        });
    }

    private void initListener() {
        message_search.setOnClickListener(this);
        tvLocation.setOnClickListener(this);//定位
        iv_alum.setOnClickListener(this);//发布
        //listview
        listView.setOnItemClickListener((parent, view, position, id) -> {
            if (position > 0) {
                Intent intent = new Intent(mContext, ParticularsPageActivity.class);
                intent.putExtra("pro_id", proListBBean.get(position - 1).getPro_id());
                intent.putExtra("type_id", proListBBean.get(position - 1).type_id);
                startActivity(intent);
            }
        });
        //gridview
        rv_type.setOnItemClickListener((parent, view, position, id) -> {
            if (null != typeListBean && typeListBean.getTypeList().size() > 0) {
                Intent intent = new Intent(context2, Roomtivity.class);
                intent.putExtra("type_id", typeListBean.getTypeList().get(position).getT_id());
                intent.putExtra("name", typeListBean.getTypeList().get(position).getT_name());
                startActivity(intent);
            }
        });

        //发布
        iv_alum.setOnClickListener(v -> {
           // Intent intent = new Intent(mContext, AlumCardActivity.class);
            Intent intent = new Intent(mContext, FansActivity.class);
           // intent.putExtra("userBean", context2.userBean);
            startActivity(intent);
            iv_alum2.setImageResource(R.drawable.fuli);
        });
    }



    EMMessageListener messageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            Logger.d("EditCreateGroup-----" + "onMessageReceived2----MainActivity");
            for (EMMessage message : messages) {
                //  DemoHelper.getInstance().getNotifier().vibrateAndPlayTone(message);
            }
           // refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            Logger.d("EditCreateGroup-----" + "onCmdMessageReceived----MainActivity");
            for (EMMessage messageCmd : messages) {
                final EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) messageCmd.getBody();
                Logger.d("MessageFragment------EditCreateGroup-----" + cmdMsgBody.action() + "----MessageFragment");
                if (cmdMsgBody.action().equals(PUBLISH_DYNAMIC)) {  //动态提醒
                    getActivity().runOnUiThread(() -> iv_alum2.setImageResource(R.drawable.fuli2));
                }
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setMessageKey(EventConstants.UPDATA_FANS_LIST);
                EventBus.getDefault().post(messageEvent);
            }

          //  refreshUIWithMessage();
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        //收到消息
        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
          //  refreshUIWithMessage();
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };

    class TypeItemListener implements BaseViewHolder.onItemCommonClickListener {
        @Override
        public void onItemClickListener(int position) {

        }

        @Override
        public void onItemLongClickListener(int position) {

        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.visiting_location:
                Intent location = new Intent(mContext, LocationActiviy.class);
                startActivityForResult(location, 100);
                // startActivity(location);
                break;
            case R.id.message_search:
                Intent intent = new Intent(mContext, SearchActiviy.class);
                startActivity(intent);
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {//当请求码是1&&返回码是2进行下面操作
            if (null == data)
                return;
            latitude = data.getDoubleExtra("latitude", 0);
            longitude = data.getDoubleExtra("longitude", 0);
            String address = data.getStringExtra("address");
            if(!TextUtils.isEmpty(address))
            if (address.contains("市")) {
                tvLocation.setText(address.split("市")[0]);
            }
            page = 1;
            getProductList(true);

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
